import { db } from '../database/db';
import { GCategory } from '../domain/g_category';

export async function getCategoryList(offset = 0, limit = 10) {
    const baseQuery = db.selectFrom('g_category');
    const [{ count }] = await baseQuery.select(db.fn.countAll().as('count')).execute();
    const total = Number(count);
    if (total === 0) {
        return { list: [], total: 0 };
    }
    const list = await baseQuery
        .selectAll()
        .orderBy('sort', 'asc')
        .offset(offset)
        .limit(limit)
        .execute();
    return { list, total };
}

export async function getCategoryById(id: number) {
    return await db.selectFrom('g_category')
        .selectAll()
        .where('id', '=', id)
        .executeTakeFirst();
}

export async function createCategory(data: GCategory) {
    const result = await db.insertInto('g_category').values(data as any).executeTakeFirst();
    return Number((result as any).insertId);
}

export async function updateCategory(id: number, data: Partial<GCategory>) {
    const result = await db.updateTable('g_category')
        .set(data)
        .where('id', '=', id)
        .executeTakeFirst();
    return Number(result.numUpdatedRows);
}

export async function deleteCategory(id: number) {
    // 物理删除，如需逻辑删除可自行扩展
    const result = await db.deleteFrom('g_category')
        .where('id', '=', id)
        .executeTakeFirst();
    return Number(result.numDeletedRows);
} 

export async function editCategoryDesc(data: any) {
    // 先根据lang和alias查询是否存在
    const result = await db.selectFrom('g_category_desc')
        .selectAll()
        .where('lang', '=', data.lang)
        .where('alias', '=', data.alias)
        .executeTakeFirst();
    console.log(result);
    if (result) {
        // 更新
        await db.updateTable('g_category_desc')
            .set(data)
            .where('lang', '=', data.lang)
            .where('alias', '=', data.alias)
            .executeTakeFirst();
    }else{
        // 插入
        await db.insertInto('g_category_desc').values(data).executeTakeFirst();
    }
}